<?php namespace App\Controllers\Admin;

use \App\App;

class Story extends App
{

    public function __construct(...$params) {
        parent::__construct();
        if (!$this->user) {
            showError("用户尚未登录，请登录后重新打开。", '', '无权限访问');
        } else if ($this->user['group']['id']!=1) {
            showError("用户无权限访问");
        }
    }

    public function index() {
        $this->view->viewTitle="小说管理";
        $this->view->desc="增加、删除、修改小说";
        $this->render("admin/story/list","admin/header");
    }

    public function table() {
        $start=$this->request->get("start");
        $length=$this->request->get("length");
        $search=$this->request->get("search");
        $order=$this->request->get("order");

        switch ($order[0]["column"]) {
            case 0:
                $sort="title";
                break;
            case 1:
                $sort="author";
                break;
            case 2:
                $sort="time";
                break;
            case 3:
            default:
                $sort="last_update";
                break;            
        }
        
        $storyModel=new \App\Models\Story();
        $storyModel->select("id,title,author,time,last_update,last_chapter,last_chapter_id,type");
        $storyModel->order($sort,$order[0]['dir']);
        if ($search[0]) {
            $storyModel->where("title",$search[0],"like")
                ->where("author",$search[0],'like',true);
            
        }
        $result=$storyModel->limit($length,$start)->datatable("recordsFiltered","data",false);
        $result["recordsTotal"]=$storyModel->countAll();
        $this->showJson($result);
    }

    public function delete($storyid)
    {
        $storyModel=new \App\Models\Story();
        $storyModel->deleteStory($storyid);
        if ($storyModel->error()) {
            $this->showJson($storyModel->error(),"Error");
        }
        $this->showJson("删除小说成功.","Success");
    }

    public function add($id=null) {
        if ($id) {
            $storyModel=new \App\Models\Story();
            $this->view->story=$storyModel->find($id);
        }
        $this->view->viewTitle="新增小说";
        $this->render("/admin/story/add","/admin/header");
    }

    public function save() {
        # code...
    }
}